package cn.zh.sql_session.controller;

import cn.zh.sql_session.domain.entity.master.Plan;
import cn.zh.sql_session.mapper.master.MasterPlanMapper;
import cn.zh.sql_session.mapper.slave.SlavePlanMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zh
 */
@RestController
@RequiredArgsConstructor
public class PlanController {

    private final MasterPlanMapper masterPlanMapper;

    private final SlavePlanMapper slavePlanMapper;

    @GetMapping("/plan/{id}")
    public List<Plan> getPlan(@PathVariable Long id){
        ArrayList<Plan> plans = new ArrayList<>();

        // Mybatis-plus
        Plan plan = masterPlanMapper.selectById(id);
        Plan slavePlan = slavePlanMapper.selectById(id);

        // Mybatis
//        Plan plan = masterPlanMapper.select(id);
//        Plan slavePlan = slavePlanMapper.select(id);
        plans.add(plan);
        plans.add(slavePlan);
        return plans;
    }

    @RequestMapping("/transaction")
    @Transactional(rollbackFor = Exception.class)
    public void tsTransaction() {
        List<Plan> plans = masterPlanMapper.selectList(null);
        Plan plan = plans.get(0);
        plan.setUpdateTime(LocalDateTime.now().plusYears(10));
        masterPlanMapper.insert(plan);
        slavePlanMapper.insert(plan);
        int a= 1/0;

    }

}
